"use strict";

/**
 * @ngdoc service
 * @name jgappApp.openFile
 * @description
 * # openFile
 * Service in the jgappApp.
 */
angular
  .module("jgappApp")
  .service("OpenFile", function (DataService, $q, openApi) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var OpenFile = {};
    OpenFile.open = function (filename) {
      var url = openApi.getPreviewUrl + filename + ".do";
      var defer = $q.defer();
      DataService.getData(url).then(function (href) {
        OpenFile.showFile(href);
        defer.resolve(href);
      });
      return defer.promise;
    };

    OpenFile.openFile = function (param) {
      var url = openApi.getFileUrl;
      return DataService.getData(url, param)
    };

    OpenFile.downLoadFile = function (filename) {
      var url = openApi.downLoadFile+"?fileName=" + filename;
      var defer = $q.defer();
      DataService.getData(url).then(function (href) {
        OpenFile.showFile(decodeURIComponent(href));
        defer.resolve(href);
        navigator.notification.alert("下载提示", "文件下载成功后将保存在下载或Download目录下")

      });
      return defer.promise;
    };

    OpenFile.showFile = function (href) {
      if (href) {
        var platform = NativeUtil.use("getDeviceInfo").system;
        if (platform == "iOS") {
          NativeUtil.use("openUrl", null, href);
        } else {
          NativeUtil.use("attachPreview", null, href);
          // window.open(href, "_system", "location=no");
        }
      }
    };

    return OpenFile;
  });
